package leetcode.code1775;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int minOperations(int[] nums1, int[] nums2) {
//		int l1 = nums1.length;
//		int l2 = nums2.length;
//		int r1 = l1 * 6;
//		int r2 = l2 * 6;
//		if (Math.max(l1, l2) > Math.min(r1, r2)) {
//			return -1;
//		}
		int sum1 = 0, sum2 = 0;
		int[] cnt1 = new int[7];
		int[] cnt2 = new int[7];
		for (int num1 : nums1) {
			sum1 += num1;
			cnt1[num1]++;
		}
		for (int num2 : nums2) {
			sum2 += num2;
			cnt2[num2]++;
		}
		if (sum1 >= sum2) {
			return this.ops(cnt1, cnt2, sum1 - sum2);
		} else {
			return this.ops(cnt2, cnt1, sum2 - sum1);
		}
	}

	private int ops(int[] subs, int[] adds, int diff) {
		int s = 6, a = 1;
		int ans = 0;
		while ((s > 1 || a < 6) && diff > 0) {
			while (s > 1 && subs[s] == 0) {
				s--;
			}
			while (a < 6 && adds[a] == 0) {
				a++;
			}
			if ((a == 7 && s > 1) || (s > 1 && s - 1 >= 6 - a)) {
				int need = (diff + s - 2) / (s - 1);
				if (need <= subs[s]) {
					return ans + need;
				}
				ans += subs[s];
				diff -= subs[s] * (s - 1);
				subs[s] = 0;
			} else if ((a < 6 && s == 0) || (a < 6 && s - 1 < 6 - a)) {
				int need = (diff + 5 - a) / (6 - a);
				if (need <= adds[a]) {
					return ans + need;
				}
				ans += adds[a];
				diff -= adds[a] * (6 - a);
				adds[a] = 0;
			}
		}
		return diff <= 0 ? ans : -1;
	}

	@Override
	public void debug4() {
		H.compare(8,
				this.minOperations(H.str2array3("[3,3,2,4,2,6,2]"), H.str2array3("[6,2,6,6,1,1,4,6,4,6,2,5,4,2,1]")));
		H.compare(3, this.minOperations(H.str2array3("[6,6]"), H.str2array3("[1]")));
		H.compare(-1, this.minOperations(H.str2array3("[1,1,1,1,1,1,1]"), H.str2array3("[6]")));
		H.compare(3, this.minOperations(H.str2array3("[1,2,3,4,5,6]"), H.str2array3("[1,1,2,2,2,2]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
